package com.xzzz.backend.blog.server.base.auth;

import com.xzzz.common.base.pojo.R;
import com.xzzz.common.base.util.ServletUtil;
import com.xzzz.irda.auth.core.authorization.Authorization;
import com.xzzz.irda.auth.core.constants.AuthConstant;
import com.xzzz.irda.auth.core.token.AccessToken;
import com.xzzz.irda.auth.server.authentication.TokenService;
import com.xzzz.irda.auth.server.pojo.LoginEventMetadata;
import com.xzzz.irda.auth.server.pojo.LoginMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 授权接口
 *
 * @author xzzz
 * @apiNote 接入授权框架的 Controller 层
 */
@RestController
public class AuthController {

    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     *
     * @return loginVO 登录信息
     */
    @PostMapping("/login")
    public R<AccessToken> login(@Validated @RequestBody LoginMetadata loginMetadata) {
        LoginEventMetadata loginEventMetadata = new LoginEventMetadata();
        loginEventMetadata.setLoginIp(ServletUtil.getIP());
        loginEventMetadata.setUserAgent(ServletUtil.getUserAgent());
        return R.ok(tokenService.login(loginMetadata, loginEventMetadata));
    }

    /**
     * 退出
     *
     * @return token 令牌信息
     */
    @GetMapping("/logout")
    public R<?> logout(@RequestHeader(AuthConstant.HEADER_AUTHORIZATION) String token) {
        tokenService.logout(token);
        return R.ok();
    }

    /**
     * 检查 token
     *
     * @return token 信息
     */
    @GetMapping("/token/check")
    public R<AccessToken> checkToken(@RequestHeader(AuthConstant.HEADER_AUTHORIZATION) String token) {
        return R.ok(tokenService.checkToken(token));
    }

    /**
     * 检查授权信息
     *
     * @return 授权主体信息
     */
    @GetMapping("/auth/check")
    public R<Authorization> checkAuthorization(@RequestHeader(AuthConstant.HEADER_AUTHORIZATION) String token) {
        return R.ok(tokenService.checkAuthorization(token));
    }
}
